package com.asiainfo.dacp.datastash.broker.core.vo;

import com.asiainfo.dacp.core.BeanFactory;
import com.asiainfo.dacp.datastash.broker.core.BrokerContext;
import com.asiainfo.dacp.datastash.broker.core.BrokerException;
import com.asiainfo.dacp.datastash.broker.core.StashUnitModel;
import com.asiainfo.dacp.datastash.broker.core.enums.ErrorCodeEnum;
import com.asiainfo.dacp.datastash.broker.core.enums.UnitStateEnum;
import com.asiainfo.dacp.util.SimpleKey;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 *
 * 单元的状态,redis中
 *
 * @author MeiKefu
 * @date 2017-12-1
 */
@Data
@NoArgsConstructor
public class StashUnit implements Serializable {

    private String unitProcId;//订单号

    private String unitCode;

    private String batchNo; //批次

    private boolean isTurnover=true;//是否翻牌

    private String state = UnitStateEnum.INIT.value();

    public StashUnit(String unitCode,String batchNo,boolean isTurnover,String unitProcId){
        this.unitCode=unitCode;
        this.batchNo=batchNo;
        this.isTurnover=isTurnover;
        if(unitProcId!=null && unitProcId.length()>0){
            this.unitProcId = unitProcId;
        }else{
            this.unitProcId = SimpleKey.genUuid(32);
        }
    }

    public void initial(){
        state = UnitStateEnum.INIT.value();
        StashUnitModel stashUnitModel = BeanFactory.getBean(StashUnitModel.class);
        stashUnitModel.updateUnit(this);
    }

    public void running(){
        state = UnitStateEnum.RUNNING.value();
        StashUnitModel stashUnitModel = BeanFactory.getBean(StashUnitModel.class);
        stashUnitModel.updateUnit(this);
    }

    public void waiting(){
        state = UnitStateEnum.BLOCKED_RELAY.value();
        StashUnitModel stashUnitModel = BeanFactory.getBean(StashUnitModel.class);
        stashUnitModel.updateUnit(this);
    }

    public void failed(){
        state = UnitStateEnum.FAIL.value();
        StashUnitModel stashUnitModel = BeanFactory.getBean(StashUnitModel.class);
        stashUnitModel.updateUnit(this);
    }
    
    public void success(){
        state = UnitStateEnum.SUCESS.value();
        StashUnitModel stashUnitModel = BeanFactory.getBean(StashUnitModel.class);
        stashUnitModel.updateUnit(this);
    }

    @JsonIgnore
    public boolean isInit(){
        return state.equals(UnitStateEnum.INIT.value());
    }

    @JsonIgnore
    public StashUnitDefine getStashUnitDefine() throws BrokerException{
        StashUnitDefine stashUnitDefine = BrokerContext.getInstance().getStashUnitDefine(unitCode);
        if(stashUnitDefine==null){
            throw new BrokerException(ErrorCodeEnum.UnitDefNull,"获取静态的StashUnitDefine失败："+unitCode);
        }
        return stashUnitDefine;
    }

}
